<template>
	<div class="home">
		<el-card :shadow="shadow">
			<div class="home-header">
				<div class="home-header-greetings">
					<div class="greetings-text">您好 {{username1}} ！祝您新的一天工作愉快。</div>
					<div class="greetings-weather">今天阴天，-12~-3° 较冷，注意加衣</div>
				</div>
				<div class="home-header-todo">
					<div v-for="todo in todoList" :key="todo">
						<div class="todo-title">
							<el-icon :color="todo.color" style="vertical-align: middle;">
								<component :is="todo.icon"></component>
							</el-icon>
							<span style="vertical-align: middle;">{{todo.name}}</span>
						</div>
						<div class="todo-num">{{todo.untreated}}/{{todo.total}}</div>
					</div>
				</div>
			</div>
		</el-card>
		<div class="home-main">
			<div class="home-main-card">
				<el-card v-for="(card,index) in cards" :key="index" :shadow="shadow" :style="{flex: 1, padding: '2rem 0', marginLeft: index==0?'0':'0.3rem'}">
					<div class="main-card-value">
						<el-icon :color="card.color" style="vertical-align: middle;">
							<component :is="card.icon"></component>
						</el-icon>
						<span class="card-value-num">{{card.total}}</span>
						<span class="card-value-ratio">, {{card.ratio}}%</span>
					</div>
					<div class="main-card-text">{{card.name}}</div>
				</el-card>
			</div>
			<div class="home-main-chart">
				<div class="chart-left">
					<el-card :shadow="shadow">
						<div id="myColumnar" style="height:500px;"></div>
					</el-card>
				</div>
				<div class="chart-right">
					<el-card :shadow="shadow">
						<div id="myPie" style="height:500px;"></div>
					</el-card>
				</div>
			</div>
		</div>
	</div>
</template>
<script setup>

import {computed, onMounted, reactive, toRefs} from 'vue';
import * as echarts from 'echarts';
import {useUserStore} from '@/store/settings';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import router from "@/router/index.js";
const myStore = useUserStore();
const user = myStore.getUser;
const username1 = user.username
console.log(user.token, "222222")
// if (user.token===null || y) {
//   await router.push('/');
// }
const MY_URL = 'http://localhost:8080/api/number';
const number = reactive({
  allNumber: 0,
  students: 0,
  teachers: 0,
  offstatus: 0,
  status: 0,
});

const warn = reactive({
  warn: 0,
  warn_rate: 0,
  serious_warn: 0,
  serious_warn_rate: 0,
  jiGuo_warn: 0,
  jiGuo_warn_rate: 0,
  seek_warn: 0,
  seek_warn_rate: 0,
  out_warn: 0,
  out_warn_rate: 0,
})

const yearData = reactive({
  one: [],
  two: [],
  three: [],
  four: [],
  five: [],
  six: [],
  seven: [],
  eight: [],
  nine: [],
  ten: [],
  eleven: [],
  twelve: [],
  nowYear: []
});


const getWarn = async () => {
  try {
    const response = await axios.get(`${MY_URL}/warn`);
    console.log('Parsed table data:', response.data);
    Object.assign(warn, response.data); // Ensure reactivity
  } catch (err) {
    ElMessage.error('数据获取失败'); // Updated error message
  }
};

const getDataYear = async () => {
  try {
    const response = await axios.get(`${MY_URL}/dataYear`);
    console.log('Parsed table data:', response.data);
    Object.assign(yearData, response.data); // Ensure reactivity
  } catch (err) {
    ElMessage.error('数据获取失败'); // Updated error message
  }
};

// Fetch data
const fetchNumbers = async () => {
  try {
    const response = await axios.get(`${MY_URL}/allNumber`);
    console.log('Parsed table data:', response.data);
    Object.assign(number, response.data); // Ensure reactivity
  } catch (err) {
    ElMessage.error('数据获取失败'); // Updated error message
  }
};

// const userStore = useAuthStore();
const state = reactive({
  username: myStore.username ?? '未登录',
  shadow: 'always',
  todoList: [],
  cards: [],
});

const {cards, shadow, todoList} = toRefs(state);

onMounted(async () => {
  await fetchNumbers(); // Ensure data is fetched before further processing
  await getWarn(); // Ensure data is fetched before further processing
  await getDataYear(); // Ensure data is fetched before further processing
  onTodoList();
  onCards();
  noColumnar();
  noPie();
});

const onTodoList = () => {
  state.todoList = [
    { name: '违纪学生数量', total: number.allNumber, untreated: number.students, icon: 'Bell', color: '#f56c6c' },
    { name: '违纪老师数量', total: number.allNumber, untreated: number.teachers, icon: 'ChatDotSquare', color: '#0084ff' },
    { name: '核销学生数量', total: number.students, untreated: number.status, icon: 'Warning', color: '#63ba4d' },
    { name: '核销老师数量', total: number.teachers, untreated: number.offstatus, icon: 'Edit', color: '#006000' },
  ];
};

const onCards = () => {
  state.cards = [
    { name: '警告', total: warn.warn, ratio: warn.warn_rate, icon: 'AddLocation', color: '#006000' },
    { name: '严重警告', total: warn.serious_warn, ratio: warn.serious_warn_rate, icon: 'Coin', color: '#f56c6c' },
    { name: '记过', total: warn.jiGuo_warn, ratio: warn.jiGuo_warn_rate, icon: 'Collection', color: '#0084ff' },
    { name: '留校查看', total: warn.seek_warn, ratio: warn.seek_warn_rate, icon: 'HelpFilled', color: '#63ba4d' },
    { name: '开除学籍', total: warn.out_warn, ratio: warn.out_warn_rate, icon: 'Histogram', color: '#67C23A' },
  ];
};

const noColumnar = () => {
  const container = document.getElementById('myColumnar');
  if (!container) {
    console.error('柱状图容器未找到');
    return;
  }
  console.log('柱状图容器:', container, '尺寸:', container.offsetWidth, container.offsetHeight);


  const myColumnar = echarts.init(container);
  myColumnar.setOption({
    legend: {},
    tooltip: {},
    color: ['#bdc3c7', '#2c3e50', '#242e42'],
    dataset: {
      dimensions: ['product', yearData.nowYear[0]-2, yearData.nowYear[0]-1, yearData.nowYear[0]],
      source: [
      yearData.one,
      yearData.two,
      yearData.three,
      yearData.four,
      yearData.five,
      yearData.six,
      yearData.seven,
      yearData.eight,
      yearData.nine,
      yearData.ten,
      yearData.eleven,
      yearData.twelve
    ],
    },
    xAxis: {
      type: 'category',
      axisTick: {
        show: false,
      },
    },
    yAxis: {
      axisTick: {
        show: false,
      },
      axisLine: {
        show: false,
      },
      splitLine: {
        show: true,
      },
    },
    series: [
      { type: 'bar' },
      { type: 'bar' },
      { type: 'bar' },
    ],
  });

  window.addEventListener('resize', myColumnar.resize);
};

const noPie = () => {
  const container = document.getElementById('myPie');
  if (!container) return;

  const myPie = echarts.init(container);
  myPie.setOption({
    title: {},
    legend: {},
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c}人 ({d}%)',
    },
    color: ['#94716B', '#6C5B7B', '#355C7D'],
    series: [
      {
        name: '违纪处分分布图',
        type: 'pie',
        radius: '90%',
        avoidLabelOverlap: false,
        roseType: 'radius',
        center: ['50%', '50%'],
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2,
        },
        label: {
          show: true,
          position: 'inner',
        },
        labelLine: {
          show: false,
        },
        data: [
          { value: warn.warn, name: '警告' },
          { value: warn.serious_warn, name: '严重警告' },
          { value: warn.jiGuo_warn, name: '记过' },
          { value: warn.seek_warn, name: '留校查看' },
          { value: warn.out_warn, name: '开除学籍' },
        ].sort((a, b) => a.value - b.value),
      },
    ],
  });

  window.addEventListener('resize', myPie.resize);
};
</script>

<style lang="scss" scoped>
	.home {
		.home-header{
			display: flex;
			justify-content: space-between;
			padding: 1rem 4rem;
max-height: 28px;
			.home-header-greetings{
				.greetings-text{
					font-size: 18px;
					padding-bottom: 0.6rem;
				}
				.greetings-weather{
					font-size: 13px;
					color: var(--t6);
				}
			}
			.home-header-todo{

				display: flex;
				div{
					padding: 0 0.6rem;
					.todo-title{
						font-size: 14px;
						color: var(--t6);
						padding-bottom: 1rem;
						.el-icon{
							padding-right: 0.2rem;
						}
					}
					.todo-num{
						font-size: 18px;
						font-weight: 700;
						//padding-left: 1.8rem;
					}
				}
			}
		}
		.home-main{
			.home-main-card{

				display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    text-align: center;
    padding: 0.3rem 0;
    overflow: hidden; /* 防止子元素溢出 */
				.main-card-value{
					font-size: 20px;
					font-weight: 700;
					.card-value-num{
						padding: 0 0.4rem;
						vertical-align: middle;
					}
					.card-value-ratio{
						vertical-align: middle;
					}
				}
				.main-card-text{
					font-size: 14px;
					padding-top: 0.4rem;
					color: var(--t6);
				}
			}
			.home-main-chart{

				display: flex;
				justify-content: space-between;
				.chart-left{
					width: 70%;
					padding-right: 0.3rem;
				}
				.chart-right{
					width: 30%;
					padding-right: 0.3rem;
          padding-bottom: 1.8rem;
				}
			}
		}
	}


</style>
